package org.epidroid.epidroid.androsoul.engine.conversation;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.util.Log;

import org.epidroid.epidroid.androsoul.engine.AndroSoul;
import org.epidroid.epidroid.androsoul.engine.contacts.NetsoulContact;

public class Conversation {

	private NetsoulContact _contact = null;
	private List<MessageItem> _messages;
	private Integer _nbUnread = 0;
	private AndroSoul _androSoul;

	public Conversation(String name, AndroSoul androsoul) {
		NetsoulContact c = _androSoul.getDictionary().get(name);
		if (c == null) {
			// TODO: throw exception
		}
		init(c, androsoul);
	}

	public Conversation(NetsoulContact contact, AndroSoul androsoul) {
		init(contact, androsoul);
	}

	public void init(NetsoulContact c, AndroSoul androsoul) {
		_androSoul = androsoul;
		_contact = c;
		_messages = new ArrayList<MessageItem>();
	}

	public void loadHistory(FileInputStream fis) {
		if (_contact == null)
			return;
		try {
			_messages.clear();
			ObjectInputStream ois = new ObjectInputStream(fis);
			Object m = null;
			do {
				try {
					m = ois.readObject();
					if ((m != null) && (m instanceof MessageItem))
						_messages.add((MessageItem) m);
				} catch (ClassNotFoundException e) {
					break;
				}
			} while (true);

			ois.close();
			fis.close();
		} catch (IOException e) {
			// No history
		}
	}

	public void saveHistory(FileOutputStream fos) {
		if (_contact == null)
			return;
		try {
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			Iterator<MessageItem> it = _messages.iterator();
			while (it.hasNext())
				oos.writeObject(it.next());
			oos.close();
			fos.close();
		} catch (IOException e) {
			// TODO: handle exception
		}
	}

	public void addMessage(MessageItem item) {
		_messages.add(item);
	}

	public void receive(MessageItem m) {
		_messages.add(m);
		Log.v(AndroSoul.LOGCAT, _contact.getName() + " sends " + m._content);
	}

	public List<MessageItem> getMessages() {
		return _messages;
	}

	public NetsoulContact getContact() {
		return _contact;
	}
	
	public Integer getNbUnread() {
		return _nbUnread;
	}
	
	public void incNbUnread() {
		_nbUnread++;
	}
	
	public void clearNbUnread() {
		_nbUnread = 0;
	}

}
